﻿using System;
using System.ComponentModel;
using System.Globalization;

namespace CodeSnippet.Options
{
    /// <summary>
    /// Style type converter that kicks in when user edits style inline in the property grid.
    /// </summary>
    public class StyleConverter : StringConverter
    {
        #region Overrides
        /// <summary>
        /// Converts the specified value object to a <see cref="T:System.String"/> object.
        /// </summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.</param>
        /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo"/> to use.</param>
        /// <param name="value">The <see cref="T:System.Object"/> to convert.</param>
        /// <returns>
        /// An <see cref="T:System.Object"/> that represents the converted value.
        /// </returns>
        /// <exception cref="T:System.NotSupportedException">
        /// The conversion could not be performed.
        /// </exception>
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            // Clean up the style to ensure the format is valid as much as possible.
            var text = base.ConvertFrom(context, culture, value) as string;
            if (text != null)
            {
                // Break up the string into lines each representing a separate property of the style.
                var lines = text.Split(new[] {";"}, StringSplitOptions.RemoveEmptyEntries);
                // Clean up each line to make sure there's no extra white spaces.
                for (var i = 0; i < lines.Length; i++)
                {
                    lines[i] = lines[i].Trim();
                }
                // Re-join the lines into a string with property separator formatting.
                text = string.Join("; ", lines).Trim();
                // Make sure to always terminate with a semi-colon, if none exists.
                text = text.EndsWith(";") ? text : string.Format(CultureInfo.InvariantCulture, "{0};", text);
            }
            // Return the resulting text.
            return text;
        }
        #endregion Overrides
    }
}
